<template>
  <div>
    <a-table
      :columns="columns"
      :data-source="data"
      :pagination="pagination"
      :loading="loading"
      :row-selection="rowSelection"
      :expanded-row-keys.sync="expandedRowKeys"
      @change="handleTableChange"
    >
      <span slot="action" slot-scope="text, record">
        <template>
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handleResource(record)">资源</a>
          <a-divider type="vertical" />
          <a @click="handleDel(record)">删除</a>
        </template>
      </span>
    </a-table>
    <a-modal title="资源配置" :width="640" :visible="visible" @cancel="() => { visible = false }">
      <a-transfer
        :data-source="resourceData"
        :titles="['Source', 'Target']"
        :target-keys="targetKeys"
        :selected-keys="selectedKeys"
        :render="item => item.name"
        :disabled="disabled"
        @change="handleTransferChange"
        @selectChange="handleTransferSelectChange"
        @scroll="handleTransferScroll"
      />
    </a-modal>
  </div>
</template>
<script>

import request from '@/utils/request'

const columns = [
  {
    title: '客户端类型',
    dataIndex: 'client_type'
  },
  {
    title: '菜单名称',
    dataIndex: 'name'
  },
  {
    title: '菜单编码',
    dataIndex: 'code',
    sorter: true
  },
  {
    title: '菜单顺序',
    dataIndex: 'order',
    sorter: true
  },
  {
    title: '菜单类型',
    dataIndex: 'type'
  },
  {
    title: '菜单路径',
    dataIndex: 'path'
  },
  {
    title: '菜单图标',
    dataIndex: 'icon'
  },
  {
    title: '是否可见',
    dataIndex: 'visible',
    filters: [
      { text: '是', value: '1' },
      { text: '否', value: '0' }
    ]
  },
  {
    title: '组件',
    dataIndex: 'component'
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' }
  }
]
const qs = require('qs')
const queryData = params => {
  return request({
    url: '/alpha-common/menus',
    method: 'get',
    params: params,
    paramsSerializer: params => {
      return qs.stringify(params, { arrayFormat: 'repeat' })
    }
  })
}
const queryResources = () => {
  return request({
    url: '/alpha-common/resources',
    method: 'get'
  })
}

const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
  },
  onSelect: (record, selected, selectedRows) => {
    console.log(record, selected, selectedRows)
  },
  onSelectAll: (selected, selectedRows, changeRows) => {
    console.log(selected, selectedRows, changeRows)
  }
}

export default {
  data () {
    return {
      data: [],
      pagination: {},
      loading: false,
      columns,
      rowSelection,
      expandedRowKeys: [],
      resourceData: [],
      targetKeys: [],
      selectedKeys: ['1', '4'],
      disabled: false,
      visible: false
    }
  },
  mounted () {
    this.fetch()
  },
  methods: {
    handleTableChange (pagination, filters, sorter) {
      console.log(pagination)
      const pager = { ...this.pagination }
      this.current = pagination.current
      this.pagination = pager
      this.fetch({
        size: pagination.pageSize,
        current: pagination.current,
        orders: (sorter && sorter.order) ? (sorter.order === 'ascend') ? sorter.field : '-' + sorter.field : null,
        // sortOrder: sorter.order,
        ...filters
      })
    },
    fetch (params = {}) {
      this.loading = true
      queryData({
        ...params
      }).then(({ data }) => {
        console.log(data)
        const treeData = []
        this.listToTree(data.records, treeData, '0')
        const pagination = { ...this.pagination }
        pagination.total = data.total
        this.loading = false
        this.data = treeData
        this.pagination = pagination
      })
    },
    handleTransferChange (nextTargetKeys, direction, moveKeys) {
      this.targetKeys = nextTargetKeys

      console.log('targetKeys: ', nextTargetKeys)
      console.log('direction: ', direction)
      console.log('moveKeys: ', moveKeys)
    },
    handleTransferSelectChange (sourceSelectedKeys, targetSelectedKeys) {
      this.selectedKeys = [...sourceSelectedKeys, ...targetSelectedKeys]

      console.log('sourceSelectedKeys: ', sourceSelectedKeys)
      console.log('targetSelectedKeys: ', targetSelectedKeys)
    },
    handleTransferScroll (direction, e) {
      console.log('direction:', direction)
      console.log('target:', e.target)
    },
    handleTransferDisable (disabled) {
      this.disabled = disabled
    },
    handleResource (record) {
      this.visible = true
      queryResources().then(({ data }) => {
        data.records.forEach(item => {
          item.key = item.id
        })
        this.resourceData = data.records
        this.targetKeys = data.records.filter(item => record.resources.indexOf(item.id) > -1).map(item => item.id)
        console.log(this.resourceData)
        console.log(this.targetKeys)
      })
    },
    listToTree (list, tree, parentId) {
      list.forEach(item => {
        // 判断是否为父级菜单
        if (item.parentId === parentId) {
          const child = {
            ...item,
            key: item.key || item.code,
            redirect: '',
            children: []
          }
          // 迭代 list， 找到当前菜单相符合的所有子菜单
          this.listToTree(list, child.children, item.id)
          // 删掉不存在 children 值的属性
          if (child.children.length <= 0) {
            delete child.children
            delete child.redirect
          } else {
            child.redirect = child.children[0].path
            console.log(child)
          }
          // 加入到树中
          tree.push(child)
        }
      })
    }
  }
}
</script>
